<!-- components/AppHeader.vue -->
<template>
    <header class="app-header">
        <!-- 第一部分 -->
        <div class="top-bar">
            <div class="container">
                <div class="left">
                    {{ $t('header.welcome') }} <span>{{ currentDate }}</span>
                </div>
                <div class="right">
                    <!-- <div class="language">
                        <span :class="{ active: locale === 'zh' }" @click="setLanguage('zh')">中</span>
                        ｜
                        <span :class="{ active: locale === 'en' }" @click="setLanguage('en')">EN</span>
                    </div> -->
                    <img src="/images/head.png" alt="language" class="icon" />
                    <div class="login">
                        <template v-if="userStore.user">
                            <span>你好，<NuxtLink :to="localePath(`/center`)">{{ userStore.user?.name }}</NuxtLink></span>
                            <span></span>
                            <span @click="userStore.logout()">| {{ $t('header.logout') }}</span>
                        </template>
                        <template v-else>
                            <span
                                @click="$router.push(localePath('/Login') + `?redirect=${encodeURIComponent(route.fullPath)}`)">{{
                                    $t('header.login') }}</span>
                            <span>/</span>
                            <span @click="$router.push(localePath('/Register'))">{{ $t('header.register') }}</span>
                        </template>
                    </div>
                </div>
            </div>
            <div class="line">
                <NuxtLink :to="localePath(`/`)">
                    <img src="/images/logo.png" alt="logo" class="logo" />
                </NuxtLink>
                <div class="search">
                    <input type="text" v-model="searchKeyword" :placeholder="$t('header.searchPlaceholder')"
                        @keyup.enter="handleSearch" />
                    <div class="icon" @click="handleSearch"><img src="/images/search.png" alt="search" /></div>
                </div>
            </div>
        </div>

        <!-- 移动端菜单按钮 -->
        <div class="mobile-menu-toggle" @click="toggleMobileMenu">
            <div class="hamburger" :class="{ 'active': isMobileMenuOpen }"></div>
        </div>

        <!-- 第二部分 -->
        <nav class="main-nav" v-show="!isMobile">
            <div class="container">
                <ul class="nav-list">
                    <li v-for="item in navItems" :key="item.name" @mouseenter="showSubNav(item)"
                        @mouseleave="hideSubNav(item)">
                        <NuxtLink @click="handleNavClick(item)" :class="{ 'active': isActive(item.path) }"
                            style="cursor: pointer;">
                            {{ item.name }}
                        </NuxtLink>
                        <ul v-if="item.children && item.showSub" class="sub-nav">
                            <li v-for="sub in item.children" :key="sub">
                                <NuxtLink :to="sub.path">{{ sub.name }}</NuxtLink>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- 移动端菜单 -->
        <div class="mobile-menu" :class="{ active: isMobileMenuOpen }">
            <ul class="nav-list">
                <li v-for="item in navItems" :key="item.name">
                    <NuxtLink @click="handleNavClick(item); closeMobileMenu()"
                        :class="{ 'active': isActive(item.path) }">
                        {{ item.name }}
                    </NuxtLink>
                </li>
            </ul>
        </div>
    </header>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
const { locale, setLocale, t } = useI18n()
const { $fetchGov } = useNuxtApp()
const userStore = useUserStore()

const route = useRoute()
const router = useRouter()
// 移动端状态
const isMobile = ref(false)
const isMobileMenuOpen = ref(false)
const searchKeyword = ref('')

// 窗口大小监听
const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768
    if (!isMobile.value) isMobileMenuOpen.value = false
}

const handleSearch = () => {
    if (searchKeyword.value.trim()) {
        router.push(
            localePath({
                path: localePath('/search'),
                query: { keyword: searchKeyword.value.trim() }
            })
        )
    } else {
        router.push(localePath('/'))
    }
}

onMounted(() => {
    checkMobile()
    window.addEventListener('resize', checkMobile)
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', checkMobile)
})

const toggleMobileMenu = () => {
    isMobileMenuOpen.value = !isMobileMenuOpen.value
}

const closeMobileMenu = () => {
    isMobileMenuOpen.value = false
}

// 路径本地化方法
const localePath = useLocalePath()

// 新增激活状态判断逻辑
const isActive = (path) => {
    const baseURL = process.client ? window.__NUXT__?.config.app.baseURL || '/' : '/';
    const localized = localePath(path);

    // 增强型标准化函数
    const normalize = (p, isTarget = false) => {
        // 处理特殊前缀
        let processed = p.replace(/^\/+|\/+$/g, '');

        // 目标路径移除baseURL前缀
        if (isTarget && baseURL !== '/') {
            const basePrefix = baseURL.replace(/^\/+|\/+$/g, '');
            processed = processed.replace(new RegExp(`^${basePrefix}`), '');
        }

        return processed || '/'; // 空路径视为根
    };

    // 获取路径（区分当前路径和目标路径）
    const current = normalize(route.fullPath);
    const target = normalize(localized, true);

    // 是否为首页判断（基于原始path参数）
    const isHomePage = path === '/';

    // 首页特殊匹配逻辑
    if (isHomePage) {
        /*
         * 匹配场景：
         * 1. 当前路径就是标准化后的目标路径（/zh → zh）
         * 2. 当前路径是纯根路径（无语言前缀）
         */
        return current === target || current === normalize('/', true);
    }

    // 常规路径匹配逻辑
    return current === target || current.startsWith(`${target}/`);
}


const currentDate = ref('')

// 导航数据处理函数
const mapChannels = (channels = []) => {
    return channels.map(item => {
        // 标准化路径处理
        const basePath = item.routerPath?.replace(/^\/|\/$/g, '') || ''; // 添加可选链操作
        return {
            // name: t(`header.nav.${basePath || 'home'}`),
            name: item.name,
            path: `/${basePath}` || '/',
            children: item.children?.map(sub => {
                const subPath = sub.routerPath?.replace(/^\/|\/$/g, '') || ''; // 添加可选链
                return {
                    // name: t(`header.nav.${subPath}`),
                    name: sub.name,
                    path: localePath(`/${basePath}/${subPath}`.replace(/\/+/g, '/'))
                }
            }) || [], // 添加空数组回退
            showSub: item.routerPath == 'members' ? false : true
        }
    })
}

// const setLanguage = async (lang) => {
//     const currentQuery = { ...route.query }
//     const newPath = localePath({
//         path: route.path,
//         query: currentQuery,
//     }, lang)
//     await setLocale(lang)
// }

const { data: channelsData, refresh } = await useAsyncData(
    `nav-channels-${new Date().getTime()}`,
    () => {
        return $fetchGov('/app/api/channel', {
            method: 'GET',
            params: {
                isNav: true,
                isIncludeChildren: true,
                isTree: true,
                offset: 0,
                _t: Date.now() // 添加时间戳
            }
        })
    })

// 手动添加首页项
const homeItem = {
    name: '首页',
    path: '/',
    children: []
};

const navItems = computed(() => {
    return mapChannels([homeItem, ...(channelsData?.value?.data || [])]) // 添加可选链操作
});

watch(locale, async () => {
    getCurrentDate();
    await refresh();
});

// 国际化日期显示
const getCurrentDate = () => {
    const date = new Date()
    const options = {
        year: 'numeric',
        month: 'long',
        day: '2-digit',
        weekday: 'long'
    }
    currentDate.value = date.toLocaleDateString(locale.value, options)

    if (locale.value === 'zh') {
        currentDate.value = currentDate.value.replace(/(日)(?=星期)/, '$1 ')
    }
}


getCurrentDate();

// 二级菜单显示控制
const showSubNav = (item) => {
    if (item.children) item.showSub = true
}
const hideSubNav = (item) => {
    if (item.children) item.showSub = false
}

const handleNavClick = (item) => {
    if (item.path === '/members') {
        if (!userStore.user) {
            ElMessageBox.confirm('您需要登录才能访问该页面', '提示', {
                confirmButtonText: '去登录',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'warning'
            }).then(() => {
                router.push(localePath('/Login') + `?redirect=${encodeURIComponent(route.fullPath)}`);
            }).catch(() => {
                // 用户取消操作
            });
        } else if (!userStore.user?.vip) {
            ElMessageBox.confirm('您需要成为会员才能访问该页面', '提示', {
                confirmButtonText: '去申请',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'warning'
            }).then(() => {
                router.push(localePath('/about/join'));
            }).catch(() => {
                // 用户取消操作
            });
        } else {
            router.push(localePath(item.path));
        }
    } else {
        router.push(localePath(item.path));
    }
};
</script>

<style lang="scss">
@use '@/assets/scss/header.scss' as *;

.language {
    span {
        cursor: pointer;

        &.active {
            font-weight: bold;
            color: #1890ff;
        }
    }
}
</style>